package Fragment;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;

import www.truongnha.com.R;
import www.truongnha.com.Students;
import www.truongnha.com.SubmitMark;
import Config.setting;
import TruongNhaLib.DatabaseHandler;
import TruongNhaLib.JSONParser;
import TruongNhaLib.Subject;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class SchoolFragment extends Fragment{
	private ArrayList<Subject> arraySubject = new ArrayList<Subject>();
	private Intent doneLoading;
	private String host = setting.getHost();
	private String url_get_all_subject = host + "api/getSubjectOfHomeroomTeacher";
	 @Override
	 public View onCreateView(LayoutInflater inflater, ViewGroup container,
			 Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.school, container, false);
		
		//Load all subject of home class
		new getAllSubject().execute(host+ "api/getSubjectOfHomeroomTeacher");
		//Create db object:
		DatabaseHandler db = new DatabaseHandler(getActivity().getBaseContext());
        // Get data for main Class
      	ArrayList<HashMap<String, String>> mainClass = db.getMainClassDetail();
      	ArrayList<HashMap<String, String>> classList = db.getClassDetails();
      	Log.d("bug", "0");
      	final ListAdapter classesAdapter = new SimpleAdapter(getActivity().getApplicationContext(), classList,
                R.layout.classes_item,
                new String[] { "classId", "name", "size", "subject", "mainteacher", "subjectId"}, new int[] {
                        R.id.cls_id ,R.id.cls_name, R.id.cls_size, R.id.cls_subject, R.id.cls_mainteacher, R.id.cls_subject_id });
        GridView grid = (GridView)view.findViewById(R.id.gridview);
        Log.d("bug", "1");
        grid.setAdapter(classesAdapter);
        final Toast toast = Toast.makeText(getActivity().getApplicationContext(), "", Toast.LENGTH_SHORT);
        Log.d("bug", "2");
        grid.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String className = ((TextView) view.findViewById(R.id.cls_name)).getText().toString();
				String classId = ((TextView) view.findViewById(R.id.cls_id)).getText().toString();
				String subject = ((TextView) view.findViewById(R.id.cls_subject)).getText().toString();
				String subjectId = ((TextView)view.findViewById(R.id.cls_subject_id)).getText().toString();
				showDialogChoiceTeachingClasses(className, classId, subject, subjectId);
			}
		});
        Log.d("bug", "3");        
        final ListAdapter mainClassAdapter = new SimpleAdapter(getActivity().getApplicationContext(), mainClass, 
        		R.layout.classes_item,
        		new String[] { "classId", "name", "size", "subject", "mainteacher"}, new int[] {
                R.id.cls_id ,R.id.cls_name, R.id.cls_size, R.id.cls_subject, R.id.cls_mainteacher });
		// selecting single ListView item
        Log.d("bug", "4");
		ListView lv = (ListView)view.findViewById(R.id.listview);
		lv.setAdapter(mainClassAdapter);
		registerForContextMenu(lv);
		// Launching new screen on Selecting Single ListItem
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String className = ((TextView) view.findViewById(R.id.cls_name)).getText().toString();
				String classId = ((TextView) view.findViewById(R.id.cls_id)).getText().toString();
				showDialogChoiceMainClass(className, classId);
			}
		});
		return view;
	 }//End oncreate
	public void showDialogChoiceTeachingClasses(final String className, final String classId, final String subject, final String subjectId) {
	    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
	    final CharSequence[] choiceList = 
	    {"Xem điểm danh lớp " +className , "Nhập điểm "+ subject +", "+ className };
	    builder.setItems(choiceList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	Intent in;
            	switch (which) {
				case 0://Diem danh
	            	in = new Intent(getActivity().getApplicationContext(), Students.class);
			        in.putExtra("class", className);
			        in.putExtra("classId", classId);					
			        startActivity(in);
					getActivity().overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
					break;
				case 1://Nhap diem
	            	in = new Intent(getActivity().getApplicationContext(), SubmitMark.class);
			        in.putExtra("class", className);
			        in.putExtra("subject", subject);
			        in.putExtra("subjectId", subjectId);					
			        startActivity(in);
					getActivity().overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
					break;
				default:
					break;
				}
            }
	    });
	    AlertDialog alert = builder.create();
	    alert.show();
	}
	public void showDialogChoiceMainClass(final String className, final String classId) {
	    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
	    builder.setTitle("Lớp chủ nhiệm");
	    int size = arraySubject.size();
	    final CharSequence[] choiceList = new CharSequence[size+1];
	    choiceList[0] = "Nhập điểm danh lớp chủ nhiệm";
	    for(int i = 0 ; i< size ; i++ ){
	    	choiceList[i+1] = "Xem điểm "+arraySubject.get(i).getSubjectName() +", " + arraySubject.get(i).getClassName();
	    }
	    builder.setItems(choiceList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            // The 'which' argument contains the index position
            	Log.d("selected", which + " = " + choiceList[which] );
            	if(which == 0){//Diem danh
	            	Intent in = new Intent(getActivity().getApplicationContext(), Students.class);
			        in.putExtra("class", className);
			        in.putExtra("classId", classId);
			        startActivity(in);
					getActivity().overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            	}else{//Xem diem
	            	Intent in = new Intent(getActivity().getApplicationContext(), SubmitMark.class);
			        in.putExtra("class", className);
			        in.putExtra("subject", arraySubject.get(which-1).getSubjectName());
			        in.putExtra("subjectId", arraySubject.get(which-1).getSubjectId());					
			        startActivity(in);            		
					getActivity().overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            	}
            }
	    });
	    AlertDialog alert = builder.create();
	    alert.show();
	}
	@Override  
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
	super.onCreateContextMenu(menu, v, menuInfo);
    	menu.add(0, 1, 0, "Nhập điểm bằng tay");
    	menu.add(0, 2, 0, "Nhập điểm bằng giọng nói");
	    menu.add(0, 3, 0, "Đọc điểm cho học sinh");
	}
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		  AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		  switch(item.getItemId()) {
		  case 1:
		        Toast.makeText(getActivity().getApplicationContext(), "id =1", Toast.LENGTH_SHORT).show();
		        Log.d("start submit mark", "start");
				// getting values from selected ListItem
		        Intent in = new Intent(getActivity().getApplicationContext(), SubmitMark.class);
		        startActivity(in);
		        return true;
		  case 2:
		        Toast.makeText(getActivity().getApplicationContext(), "id =2", Toast.LENGTH_SHORT).show();
		        return true;
		  case 3:
		        Toast.makeText(getActivity().getApplicationContext(), "id =3", Toast.LENGTH_SHORT).show();
		        return true;
		  default:
			  //Do nothing
			  return true;
		  }
	}//End
	class getAllSubject extends AsyncTask<String, Void, Void>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			doneLoading = new Intent();
	        doneLoading.setAction("DONE_LOADING_ACTION");
	        doneLoading.putExtra("doneLoading", false);
	        getActivity().getApplicationContext().sendBroadcast(doneLoading);
		}
		@Override
		protected Void doInBackground(String... params) {
	        JSONArray json_array = new JSONParser().getJSONArray(params[0]);
			int size = json_array.length();
        	arraySubject.clear();
			try {
	        	for(int i = 0;i<size; i++){
	        		arraySubject.add(new Subject(json_array.getJSONObject(i)));
	        	}
			} catch (JSONException e) {
				e.printStackTrace();
			}
        	return null;
		}
	
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			//Broadcast to main activity when done loading
			doneLoading = new Intent();
	        doneLoading.setAction("DONE_LOADING_ACTION");
	        doneLoading.putExtra("doneLoading", true);
	        getActivity().getApplicationContext().sendBroadcast(doneLoading);	
	        Log.d("done load all subject", "done");
		}
	}//End class getAllSubject

}
